<?php


namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => [
                'required',
            ],
            'password' => [
                'required',
            ],
        ]);

        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }
        $student['username'] = $request->get('username');
        $student['password'] = $request->get('password');

        if (! $token = auth()->attempt($student)) {
            return response()->json(['error' => '用户名或密码错误，请重新输入'], 401);
        }

        return $this->respondWithToken($token);
    }

    public function me()
    {
        $user = auth()->user();
        $result['name'] = $user->name;
        $result['mechanismName'] = $user->mechanism->name;
        $result['className'] = $user->classes->name;
        return response()->json($result);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
